package com.gitee.cui.security.netty.securechat;

import com.gitee.cui.config.SystemConfig;
import com.gitee.cui.ssl.SSLContextHelper;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;
import org.apache.commons.lang.StringUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Netty版安全聊天客户端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/5 16:15
 **/
public class SecureChatClient {

    public static void startClient() {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new SecureChatInitializer());
            ChannelFuture future = bootstrap.connect(SystemConfig.SOCKET_SERVER_IP, SystemConfig.SOCKET_SERVER_PORT);
            future.sync();
            Channel channel = future.channel();
            // 从控制台获取输入的内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            ChannelFuture writeFuture = null;
            while (true) {
                String line = reader.readLine();
                if (StringUtils.isNotBlank(line)) {
                    writeFuture = channel.writeAndFlush(line + "\r\n");
                }
                if ("bye".equalsIgnoreCase(line)) {
                    channel.closeFuture().sync();
                    break;
                }
            }
            // 发送完成之后，再接收下一轮的输入
            if (writeFuture != null) {
                writeFuture.sync();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

    private static class SecureChatInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SSLContext context = SSLContextHelper.createClientSSLContext();
            SSLEngine engine = context.createSSLEngine();
            engine.setNeedClientAuth(true);
            engine.setUseClientMode(true);
            SslHandler sslHandler = new SslHandler(engine);
            // 添加ssl处理器
            pipeline.addLast("ssl", sslHandler);
            // 添加分包处理器
            pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
            // 添加字符串解码器
            pipeline.addLast("decoder", new StringDecoder());
            // 添加字符串编码器
            pipeline.addLast("encoder", new StringEncoder());
            // 添加客户端会话处理器
            pipeline.addLast("handler", new SecureChatHandler());
        }
    }
}
